<?php

/**
 * Created by PhpStorm.
 * User: meiyun1
 * Date: 2017/3/13
 * Time: 上午11:20
 */

namespace App\Http\Controllers\Web\ActivityRecords;

use App\App\Services\Web\UserService;
use App\Contracts\Repositories\ActivityRepository;
use App\Entities\ActivityModel;
use App\Entities\Participant;
use App\Exceptions\ExceptionCode;
use App\Models\Activity\ActivityService as ModelActivityService;
use App\Models\ActivityPrize\ActivityPrizeService;
use App\Models\ActivityRecord\ActivityRecordService;
use App\Models\Prize\Prize;
use App\Models\PrizeType\PrizeType;
use Illuminate\Http\Request;
use Maatwebsite\Excel\Facades\Excel;

class ActivityRecordsController extends \App\Http\Controllers\Controller
{
    public function index(\Illuminate\Http\Request $request, ModelActivityService $activityService)
    {
        $activity_id = $request->query->get('activity_id', '');
        $activity = $activityService->findOne($activity_id);

        return view(
            'web.activityRecords.list',
            [
                'activity_id' => $activity_id,
                'activities'  => $activityService->findByActivityModelType(
                    ActivityModel::TYPE_DRAW,
                    ['id', 'name'],
                    true
                ),
                'activity'    => $activity,
            ]
        );
    }

    public function activityRecords(Request $request, ActivityRecordService $activityRecordService)
    {
        $startTime = $request->query->get('start', date('Y-m-d', strtotime('-7 day')));
        $endTime = $request->query->get('end', date('Y-m-d', strtotime('+1 day')));
        $start = intval($request->query->get('offset', 0));
        $limit = intval($request->query->get('limit', 10));
        $mobile = $request->query->get('mobile');
        $activity_id = $request->query->get('activity_id');
        $sort = $request->query->get('sort', 'created_at');
        $order = $request->query->get('order', 'desc');
        $sortArray = [[$sort, $order]];
        $conditions = [];
        $conditions[] = ['created_at', '<=', $endTime];
        $conditions[] = ['created_at', '>', $startTime];
        $conditions[] = ['prize_id', '!=', null];
        if (isset($mobile) && !empty($mobile)) {
            $unique_id = Participant::query()
                ->where('mobile', $mobile)
                ->value('uniqueid');
            $conditions[] = ['openid', $unique_id];
            // $conditions[] = ['mobile', $mobile];
        }
        if (isset($activity_id) && !empty($activity_id)) {
            $conditions[] = ['activity_id', $activity_id];
        }
        $list = $activityRecordService->findByConditionsPage($conditions, $sortArray, $start, $limit);

        foreach ($list as $item) {
            $item->activity;
            $item->prize;
            $item->prize->prizeType;
            $item->participant;

            if ($item->prize->extends) {
                $item->prize->fileds = \GuzzleHttp\json_decode($item->prize->extends, true);
            } else {
                $item->prize->fileds = [];
            }

            unset($item->prize->extends);
        }

        $total = $activityRecordService->count($conditions);

        return $this->respondJson([
            'total' => $total,
            'rows'  => $list->toArray(),
        ]);
    }

    public function export(
        Request $request,
        ActivityRepository $activityRepository,
        UserService $userService,
        ActivityRecordService $activityRecordService)
    {
        $this->validate($request, [
            'activity_id' => 'required',
        ], [
            'activity_id.required' => '请填写活动ID',
        ]);
        $activityId = $request->query->get('activity_id');
        $activity = $activityRepository->findGroupActivityById($activityId, $userService->getGroupCode());
        if (!$activity) {
            return $this->respondJson([
                'code'    => ExceptionCode::GENERAL,
                'message' => '活动不存在！',
            ]);
        }
        $exportData = $activityRecordService->exportData($activityId);
        $activity = is_null($exportData['activity']) ? '未知' : $exportData['activity'];
        $filename = '【' . $activity . '】活动中奖列表' . date('Y-m-d H:i:s');

        Excel::create($filename, function ($excel) use ($exportData) {
            $dataRecords = $exportData['records'];
            $prizes = $exportData['prizes'];
            if ($dataRecords) {
                foreach ($dataRecords as $key => $dataRecord){
                    $excel->sheet($prizes[$key], function ($sheet) use ($dataRecord) {
                        $sheet->fromArray($dataRecord);
                    });
                }
            }
        })->download('xlsx');
    }

    public function activityUpdate(Request $request, ActivityRecordService $activityRecordService, ActivityPrizeService $activityPrizeService)
    {
        $record_id = $request->request->get('id');
        $activity_record = $activityRecordService->findByConditionsPage([['id', $record_id]])->first();
        $activity_record->is_exchange = 1;
        $activity_record->save();

        return $this->respondJson([
            'message' => '保存成功',
        ]);
    }
}
